package com.masterclient.app.businessmodule.homemodule.fragment;

import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.status.StatusBarUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.uikit.header.MyRefreshHead;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.homemodule.adapter.MineMeetAdapter;
import com.masterclient.app.businessmodule.homemodule.adapter.NoticeAdapter;
import com.masterclient.app.businessmodule.homemodule.contract.MineContract;
import com.masterclient.app.businessmodule.homemodule.contract.MinePresenter;
import com.masterclient.app.modules.income.model.MineDataBean;
import com.masterclient.app.utils.CommonUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation;

public class MineFragment extends BaseFragment<MinePresenter> implements MineContract.View {

    public static String TAG = "MineFragment";

    @BindView(R.id.view_head)
    View viewHead;
    @BindView(R.id.swipeLayout)
    SmartRefreshLayout swipeLayout;
    @BindView(R.id.view_notice)
    View viewNotice;
    @BindView(R.id.noticeRecyclerView)
    RecyclerView noticeRecyclerView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.view_no_data)
    View viewNoData;

    private int mPosition = 0;
    private MineMeetAdapter mineMeetAdapter;
    private NoticeAdapter noticeAdapter;
    private MineDataBean mineDataBean;
    private KProgressHUD mCommitLoading;
    private List<MineDataBean.NoticesItem> notices = new ArrayList<>();

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_mine, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        //2.设置状态栏
        StatusBarUtils.immersive(getActivity());
        StatusBarUtils.setPaddingSmart(getActivity(), viewHead);

        swipeLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
        swipeLayout.setOnRefreshListener(refreshLayout -> {
            mPresenter.getCustomerInfo();
        });

        mPresenter.getCustomerInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @OnClick({R.id.tv_exit_login, R.id.view_code, R.id.view_more_notice})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_exit_login:
                baseShowCommitLoading("");
                mPresenter.logout();
                break;
            case R.id.view_code:
                if (mineDataBean != null) {
                    CommonUtil.goAnyWhere(mContext,mineDataBean.cardUrl,"","","","","");
                }
                break;
            case R.id.view_more_notice:
                if (mineDataBean != null) {
                    CommonUtil.goAnyWhere(mContext, mineDataBean.noticeIndexUrl, "", "", "", "", "");
                }
                break;
        }
    }

    @Override
    public void getCustomerInfoSuccess(MineDataBean mineDataBean) {
        if (swipeLayout != null) {
            swipeLayout.finishRefresh();
        }
        this.mineDataBean = mineDataBean;
        tvName.setText(mineDataBean.nickname);
        tvPhone.setText(mineDataBean.mobile);
        ViewTransformUtil.glideImageView(getActivity(), mineDataBean.headImgUrl, ivHead,
                new CropCircleWithBorderTransformation(0, 0x0A3D2529), R.mipmap.icon_mine_head);

        if (mineDataBean.notices != null && mineDataBean.notices.size() > 0) {
            viewNotice.setVisibility(View.VISIBLE);
            //最多默认显示前5条
            notices.clear();
            if (mineDataBean.notices.size() > 5) {
                for (int i = 0; i < 5; i++) {
                    notices.add(mineDataBean.notices.get(i));
                }
            } else {
                for (int i = 0; i < mineDataBean.notices.size(); i++) {
                    notices.add(mineDataBean.notices.get(i));
                }
            }
            noticeRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            noticeAdapter = new NoticeAdapter(notices);
            noticeAdapter.setOnItemClickListener((adapter, view, position) -> {
                MineDataBean.NoticesItem item = mineDataBean.notices.get(position);
                CommonUtil.goAnyWhere(mContext, item.noticeUrl, "", "", "", "", "");
            });
            noticeAdapter.bindToRecyclerView(noticeRecyclerView);
        } else {
            viewNotice.setVisibility(View.GONE);
        }
        if (mineDataBean.subscribeEvents != null && mineDataBean.subscribeEvents.size() > 0) {
            viewNoData.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            mineMeetAdapter = new MineMeetAdapter(mineDataBean.subscribeEvents);
            mineMeetAdapter.setOnItemClickListener((adapter, view, position) -> {
                MineDataBean.HotEventItem item = mineDataBean.subscribeEvents.get(position);
                CommonUtil.goAnyWhere(mContext, item.eventUrl, "", "", "", "", "");
            });
            mineMeetAdapter.setOnClickStatusListener((eventId, position) -> {
                mPosition = position;
                mPresenter.cancelSubscribe(eventId);
            });
            mineMeetAdapter.bindToRecyclerView(recyclerView);
        } else {
            viewNoData.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getCustomerInfoFailed(String msg) {
        if (swipeLayout != null) {
            swipeLayout.finishRefresh(false);
        }
        showToast(msg);
    }

    @Override
    public void logout() {
        baseHiddenCommitLoading();
        UserDataManager.getInstance().clearLoginInfo();
        ARouter.getInstance().build(AroutePath.MAIN_ACTIVITY).withString("position", "0").navigation();
    }

    @Override
    public void logoutFailed(String msg) {
        baseHiddenCommitLoading();
        showToast(msg);
    }

    @Override
    public void cancelSuccess() {
        mPresenter.getCustomerInfo();
    }

    @Override
    public void cancelFailed(String msg) {
        showToast(msg);
    }

    /**
     * 显示提交指示器
     */
    public void baseShowCommitLoading(String msg) {
        if (mCommitLoading == null) {
            mCommitLoading = KProgressHUD.create(getActivity())
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
            mCommitLoading.setBackgroundColor(Color.parseColor("#80000000"));
            mCommitLoading.setCancellable(false);
            if (msg != null && msg.length() > 0) {
                mCommitLoading.setLabel(msg);
            }
            if (!getActivity().isFinishing() && !mCommitLoading.isShowing()) {
                mCommitLoading.show();
            }
        } else if (!mCommitLoading.isShowing() && getActivity().hasWindowFocus()) {
            if (!!getActivity().isFinishing()) {
                mCommitLoading.show();
            }
        }
    }

    /**
     * 隐藏提交指示器
     */
    public void baseHiddenCommitLoading() {
        if (mCommitLoading != null) {
            try {
                if (mCommitLoading.isShowing() && !getActivity().isFinishing()) {
                    mCommitLoading.dismiss();
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        mCommitLoading = null;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mPresenter.getCustomerInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
